class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def largestBSTSubtree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.max_value = 1

        def search(node):
            now_flag = True
            now_left = node.val
            now_right = node.val
            now_count = 1
            if node.left:
                left_flag, left_min, left_max, left_count = search(node.left)
                if left_flag and left_max < node.val:
                    now_left = left_min
                    now_count += left_count
                else:
                    now_flag = False
            if node.right:
                right_flag, right_min, right_max, right_count = search(node.right)
                if right_flag and node.val < right_min:
                    now_right = right_max
                    now_count += right_count
                else:
                    now_flag = False
            if now_flag:
                self.max_value = max(self.max_value, now_count)
            return now_flag, now_left, now_right, now_count

        search(root)
        return self.max_value
